package com.base.control;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.base.model.Bean2Json;
import com.base.model.FindViewable;
import com.base.util.BackgroundSetter;
import com.base.util.ConstantResource;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;

import java.io.Serializable;
import java.lang.reflect.Field;

public abstract class MFragmentSupport extends Fragment  implements RequestCallback, FindViewable {
	private boolean created = false;
	private LayoutInflater inflater;
	private ViewGroup viewGroup;
	private View contextView;
	private Callback callbacks;
    protected boolean imageLoaderSetted;
    protected  MActivitySupport mactivity;
    private int contextViewid;
    private String name = "";
    private boolean showActionbar = true;
	
	protected abstract void create(Bundle savedInstanceState);

    public MActivitySupport getMactivity() {
        return mactivity;
    }

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup viewGroup, Bundle savedInstanceState) {
		this.inflater = inflater;
		this.viewGroup = viewGroup;
        //防止“一女二嫁”
        if (contextView != null && contextView.getParent() != null) { ((ViewGroup)contextView.getParent()).removeView(contextView); }
		if(!this.created) {
			create(savedInstanceState);
			created = true;
		}

		return contextView;
	}
	
	//it must called in create
	public void setContentView(int contextView) {
		this.contextView = this.inflater.inflate(contextView, viewGroup, false);
        this.contextViewid = contextView;
	}

    @Override
    public void onResume() {
        super.onResume();
        if(showActionbar)
            this.setActionBar(getMactivity().getSupportActionBar(), getMactivity());
        //检查是否在此context是否有自定义的背景设置
        BackgroundSetter.checkAndSet(this, contextViewid);
    }

    @Override
    public void onStop() {
        super.onStop();
        BackgroundSetter.destroy(this);
    }


    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        if(activity instanceof Callback) {
            callbacks = (Callback)activity;
        }
        if(activity instanceof MActivitySupport) {
            mactivity = (MActivitySupport)activity;
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        callbacks = null; //onDetach之后，置为null，不要影响到callbask所引用对象的GC
        mactivity = null;
        try {
            Field childFragmentManager = Fragment.class
                    .getDeclaredField("mChildFragmentManager");
            childFragmentManager.setAccessible(true);
            childFragmentManager.set(this, null);

        } catch (NoSuchFieldException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    //自定义actionBar
    public void setActionBar(ActionBar actionBar, Context context) {

    }
	
	/**
	 * 便于操作
	 * @param id
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public <T> T findViewById(int id) {
		View res = null;
		if(this.contextView != null)
			res = this.contextView.findViewById(id);
		return (T)res;
	}


    //通用intent数据封装
    public void startForResultWithData(int requestCode, Bundle data, Class<? extends Activity> claz) {
        Intent intent = new Intent(getContext(), claz);
        if(data != null) {
            intent.putExtras(data);
        }
        startActivityForResult(intent, requestCode);
    }

    public int getStartType() {
        int ret = -1;
        Bundle data = getArguments();
        if(data != null)
            ret = data.getInt(ConstantResource.START_TYPE, -1);
        return ret;
    }

    public Serializable getStartData() {
        Serializable ret = null;
        Bundle data = getArguments();
        if(data != null) {
            ret = data.getSerializable(ConstantResource.START_DATA);
        }
        return ret;
    }


    //自动大图背景设置机制
    @Override
    public View findViewIdForSetBackground(int resid) {
        return findViewById(resid);
    }
    @Override
    public Context getContextForSetBackground() {
        return getActivity();
    }
    @Override
    public void setImageView(ImageView iv, int resid, MActivitySupport.ImageLoaderType type, boolean cleanCache) {
        getMactivity().setImageView(iv, resid, type, cleanCache);
    }

    @Override
    public void setImageView(ImageView iv, int replaceId, MActivitySupport.ImageLoaderType type, boolean cleanCache, String imgId,
                             int w, int h, Integer loadingImg, boolean isRound, boolean isFadeIn, ImageLoadingListener imageLoadingListener) {
        getMactivity().setImageView(iv, replaceId, type, cleanCache, imgId, w, h, loadingImg, isRound, isFadeIn, imageLoadingListener);
    }

    public Context getContext(){
		return getActivity();
	}
	
	public void callback() {
		if(callbacks != null) {
			callbacks.callback();
		}
	}

    //网络请求回调，子类可选封装
    @Override
    public void onRequestError(Integer errcode, String errmsg) {

    }

    @Override
    public void onRequestSuccess(Bean2Json data) {

    }

    /*
         * setter & getter
         */
	public LayoutInflater getInflater() {
		return inflater;
	}

	public void setInflater(LayoutInflater inflater) {
		this.inflater = inflater;
	}

	public View getContextView() {
		return contextView;
	}

	public void setContextView(View contextView) {
		this.contextView = contextView;
	}

	public ViewGroup getViewGroup() {
		return viewGroup;
	}

	public void setViewgroup(ViewGroup viewGroup) {
		this.viewGroup = viewGroup;
	}

	public boolean isCreated() {
		return created;
	}

	public void setCreated(boolean created) {
		this.created = created;
	}


    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public boolean isShowActionbar() {
        return showActionbar;
    }

    public void setShowActionbar(boolean showActionbar) {
        this.showActionbar = showActionbar;
    }
}
